
<template>
  <div id="userManagePage">
    <a-card class="user-manage-card" :bordered="false">
      <!-- 搜索表单 -->
      <a-form layout="inline" :model="searchParams" @finish="doSearch" class="search-form">
        <a-form-item label="账号">
          <a-input v-model:value="searchParams.userAccount" placeholder="输入账号" allow-clear />
        </a-form-item>
        <a-form-item label="用户名">
          <a-input v-model:value="searchParams.userName" placeholder="输入用户名" allow-clear />
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" html-type="submit">
              <template #icon><SearchOutlined /></template>
              搜索
            </a-button>
            <a-button @click="resetSearch">
              <template #icon><ReloadOutlined /></template>
              重置
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
      <a-divider style="margin: 16px 0" />
      <!-- 表格 -->
      <a-table
        :columns="columns"
        :data-source="data"
        :pagination="pagination"
        @change="doTableChange"
        :loading="loading"
        :rowKey="record => record.id"
        bordered
      >
    <template #headerCell="{ column }">
      <template v-if="column.key === 'name'">
        <span>
          <smile-outlined />
          Name
        </span>
      </template>
    </template>

    <template #bodyCell="{ column, record }">
      <template v-if="column.dataIndex === 'userAvatar'">
        <a-avatar :src="record.userAvatar" :size="64" shape="square" />
      </template>
      <template v-else-if="column.dataIndex === 'userRole'">
        <a-tag :color="record.userRole === 'admin' ? 'green' : 'blue'">
          {{ record.userRole === 'admin' ? '管理员' : '普通用户' }}
        </a-tag>
      </template>
      <template v-else-if="column.dataIndex === 'createTime'">
        <a-tooltip :title="dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss')">
          {{ dayjs(record.createTime).format('YYYY-MM-DD') }}
        </a-tooltip>
      </template>
      <template v-else-if="column.key === 'action'">
        <a-space>
          <a-button type="primary" size="small" @click="showEditModal(record)">
            <template #icon><EditOutlined /></template>
            编辑
          </a-button>
          <a-popconfirm
            title="确定要删除此用户吗?"
            ok-text="确定"
            cancel-text="取消"
            @confirm="doDelete(record.id)"
          >
            <a-button type="primary" danger size="small">
              <template #icon><DeleteOutlined /></template>
              删除
            </a-button>
          </a-popconfirm>
        </a-space>
      </template>
    </template>
  </a-table>
    </a-card>

    <!-- 编辑用户对话框 -->
    <a-modal
      v-model:visible="editModalVisible"
      title="编辑用户"
      @ok="handleEditOk"
      @cancel="handleEditCancel"
      :confirmLoading="editModalLoading"
    >
      <a-form :model="editForm" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
        <a-form-item label="用户ID">
          <a-input v-model:value="editForm.id" disabled />
        </a-form-item>
        <a-form-item label="账号">
          <a-input v-model:value="editForm.userAccount" disabled />
        </a-form-item>
        <a-form-item label="用户名">
          <a-input v-model:value="editForm.userName" placeholder="请输入用户名" />
        </a-form-item>
        <a-form-item label="头像URL">
          <a-input v-model:value="editForm.userAvatar" placeholder="请输入头像URL" />
        </a-form-item>
        <a-form-item label="用户简介">
          <a-textarea v-model:value="editForm.userProfile" placeholder="请输入用户简介" :rows="4" />
        </a-form-item>
        <a-form-item label="用户角色">
          <a-select v-model:value="editForm.userRole">
            <a-select-option value="user">普通用户</a-select-option>
            <a-select-option value="admin">管理员</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>


</template>
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { deleteUser, listUserVoByPage, getUserById, updateUser } from '@/api/userController.ts'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import { SearchOutlined, ReloadOutlined, DeleteOutlined, EditOutlined } from '@ant-design/icons-vue'
const columns = [
  {
    title: 'id',
    dataIndex: 'id',
  },
  {
    title: '账号',
    dataIndex: 'userAccount',
  },
  {
    title: '用户名',
    dataIndex: 'userName',
  },
  {
    title: '头像',
    dataIndex: 'userAvatar',
  },
  {
    title: '简介',
    dataIndex: 'userProfile',
  },
  {
    title: '用户角色',
    dataIndex: 'userRole',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
  },
  {
    title: '操作',
    key: 'action',
  },
]
// 数据
const data = ref<API.UserVO[]>([])
const total = ref(0)
const loading = ref(false)

// 编辑模态框相关
const editModalVisible = ref(false)
const editModalLoading = ref(false)
const editForm = reactive<API.UserUpdateRequest>({
  id: '',
  userName: '',
  userAvatar: '',
  userProfile: '',
  userRole: '',
})

// 搜索条件
const searchParams = reactive<API.UserQueryRequest>({
  pageNum: 1,
  pageSize: 10,
})

// 重置搜索
const resetSearch = () => {
  searchParams.userAccount = undefined
  searchParams.userName = undefined
  searchParams.pageNum = 1
  fetchData()
}

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    const res = await listUserVoByPage({
      ...searchParams,
    })
    if (res.data.data) {
      data.value = res.data.data.records ?? []
      total.value = res.data.data.totalRow ?? 0
    } else {
      message.error('获取数据失败，' + res.data.message)
    }
  } catch (error) {
    message.error('获取数据失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}
// 分页参数
const pagination = computed(() => {
  return {
    current: searchParams.pageNum ?? 1,
    pageSize: searchParams.pageSize ?? 10,
    total: total.value,
    showSizeChanger: true,
    showTotal: (total: number) => `共 ${total} 条`,
  }
})
// 表格变化处理
const doTableChange = (page: any) => {
  searchParams.pageNum = page.current
  searchParams.pageSize = page.pageSize
  fetchData()
}
// 获取数据
const doSearch = () => {
  // 重置页码
  searchParams.pageNum = 1
  fetchData()
}
// 删除数据
const doDelete = async (id: string) => {
  if (!id) {
    return
  }
  const res = await deleteUser({ id })
  if (res.data.code === 0) {
    message.success('删除成功')
    // 刷新数据
    fetchData()
  } else {
    message.error('删除失败')
  }
}


// 显示编辑模态框
const showEditModal = async (record: API.UserVO) => {
  editModalVisible.value = true
  editModalLoading.value = true

  try {
    // 获取用户详细信息
    const res = await getUserById({ id: record.id })
    if (res.data.code === 0 && res.data.data) {
      const userData = res.data.data
      // 填充表单
      editForm.id = userData.id
      editForm.userAccount = userData.userAccount
      editForm.userName = userData.userName
      editForm.userAvatar = userData.userAvatar
      editForm.userProfile = userData.userProfile
      editForm.userRole = userData.userRole
    } else {
      message.error('获取用户信息失败')
    }
  } catch (error) {
    message.error('获取用户信息失败，请检查网络连接')
  } finally {
    editModalLoading.value = false
  }
}

// 处理编辑确认
const handleEditOk = async () => {
  if (!editForm.id) {
    message.error('用户ID不能为空')
    return
  }

  editModalLoading.value = true
  try {
    const res = await updateUser(editForm)
    if (res.data.code === 0) {
      message.success('更新用户信息成功')
      editModalVisible.value = false
      // 刷新数据
      fetchData()
    } else {
      message.error('更新用户信息失败：' + res.data.message)
    }
  } catch (error) {
    message.error('更新用户信息失败，请检查网络连接')
  } finally {
    editModalLoading.value = false
  }
}

// 处理编辑取消
const handleEditCancel = () => {
  editModalVisible.value = false
}

// 页面加载时请求一次
onMounted(() => {
  fetchData()
})

</script>
<style scoped>
.user-manage-card {
  margin-bottom: 24px;
  box-shadow: 0 1px 2px -2px rgba(0, 0, 0, 0.16),
              0 3px 6px 0 rgba(0, 0, 0, 0.12),
              0 5px 12px 4px rgba(0, 0, 0, 0.09);
  border-radius: 8px;
}

.search-form {
  margin-bottom: 16px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

:deep(.ant-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.ant-table-thead > tr > th) {
  background-color: #f0f5ff;
  font-weight: 600;
}

:deep(.ant-table-tbody > tr:hover > td) {
  background-color: #e6f7ff;
}

:deep(.ant-pagination) {
  margin-top: 16px;
}

:deep(.ant-card-head) {
  border-bottom: 2px solid #1890ff;
  padding-left: 16px;
}

:deep(.ant-card-head-title) {
  font-size: 18px;
  font-weight: 600;
  color: #1890ff;
}

@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
  }

  :deep(.ant-form-item) {
    margin-bottom: 12px;
  }
}

@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
  }

  :deep(.ant-form-item) {
    margin-bottom: 12px;
  }
}
</style>
